/*
 * Copyright (C) 2009 TeamCity Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.cdmdotnet.android.teamcity;

import java.io.IOException;
import java.util.Iterator;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;

import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.test.suitebuilder.TestSuiteBuilder.FailedToCreateTests;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;

import com.cdmdotnet.android.teamcity.model.TCBuildProxy;
import com.cdmdotnet.android.teamcity.model.TCBuildTypeProxy;
import com.cdmdotnet.android.teamcity.model.TCProjectProxy;
import com.cdmdotnet.android.teamcity.R;

public class ProjectWidgetUpdateService extends Service {

	private static String PREFS_NAME = "WidgetPrefsFile";
	
	@Override
	public IBinder onBind(Intent intent) {
        // We don't need to bind to this service
		return null;
	}

	/* (non-Javadoc)
	 * @see android.app.Service#onStart(android.content.Intent, int)
	 */
	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);

		final AppWidgetManager widgetManager = AppWidgetManager.getInstance(ProjectWidgetUpdateService.this);
		final int appWidgetId = intent.getIntExtra("widget.id", AppWidgetManager.INVALID_APPWIDGET_ID);

		Log.d("TeamCity", "ProjectUpdateService appWidgetId=" + appWidgetId + "uri=" + intent.getDataString());
		
       	final TCProjectProxy project = new TCProjectProxy(intent);

        // Asynchronously load buildType
        new AsyncLoader() {
			private int failuresCount = 0;
        	
			@Override
			protected void load() throws ClientProtocolException, IOException, JSONException {
				project.load();
           		for (Iterator<TCBuildTypeProxy> buildTypes = project.getBuildTypes().iterator(); buildTypes.hasNext();) {
           			TCBuildTypeProxy buildType = buildTypes.next();
           			buildType.load();
           			failuresCount += buildType.getLastBuildStatus() == TCBuildProxy.BUILD_FAILURE ? 1:0;
           		}
			}
			
			@Override
			public void onLoadingStarted() {
		        RemoteViews views = new RemoteViews(getPackageName(), R.layout.project_widget);
		        views.setTextViewText(R.id.projectNameTextView, project.getData().getStringExtra(TCProjectProxy.NAME));
		// infinite progress bar
		        views.setViewVisibility(R.id.progress_loading_view, View.VISIBLE);
		        views.setViewVisibility(R.id.progress_view, View.GONE);
		        
           		// Push update for this widget to the home screen
                widgetManager.updateAppWidget(appWidgetId, views);
			}

			@Override
			public void onLoadingFinished(int status, String errMessage) {
		        RemoteViews views = new RemoteViews(getPackageName(), R.layout.project_widget);
		        views.setTextViewText(R.id.projectNameTextView, project.getData().getStringExtra(TCProjectProxy.NAME));
		        views.setViewVisibility(R.id.progress_view, View.VISIBLE);
		        views.setViewVisibility(R.id.progress_loading_view, View.GONE);
                switch (status) {
                case LOADING_FAILED:
            		//TODO:
            		views.setProgressBar(R.id.progress, 100, 0, false);
                    views.setTextViewText(R.id.failedBuildsTextView, "Disconnected.");
              		views.setImageViewResource(R.id.widgetStatusIcon, R.drawable.teamcity_small_bw);
            		break;
                case LOADING_SUCCEDED:
                    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
                    int oldFailuresCount = settings.getInt("failuresCount_"+appWidgetId, 0);
                    int delta = failuresCount - oldFailuresCount;
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putInt("failuresCount_"+appWidgetId, failuresCount);
                    editor.commit();
                    
                	int totalCount = project.getBuildTypes().size();
             		views.setProgressBar(R.id.progress, 100, 100 - 100*failuresCount/totalCount, false);
             		if (failuresCount > 0) {
                        views.setTextViewText(R.id.failedBuildsTextView, "Failed: " + failuresCount + "/" + totalCount + 
                        		" (" + Math.abs(delta) + (delta >=0 ? " new)" : " fixed)"));
             		} else {
                        views.setTextViewText(R.id.failedBuildsTextView, "Successful");

             		}
             		views.setImageViewResource(R.id.widgetStatusIcon, R.drawable.teamcity_small);
             		// Prepare pending intent to launch BuildsListPage activity on click on widget
                    PendingIntent pi = PendingIntent.getActivity(ProjectWidgetUpdateService.this, 0, project.getData(), 0);
                    views.setOnClickPendingIntent(R.id.ProjectWidget, pi);
             		break;
                }
           		// Push update for this widget to the home screen
                
                widgetManager.updateAppWidget(appWidgetId, views);
                // We are done. Stop this service
                Log.d("TeamCity", "ProjectUpdateService is done. Stopping...");
                stopSelf();
			}
		}.asyncLoad();
   }
}
